<?php
/**
 * Yotaku
 * @author Creatint<creatint@163.com>
 * @copyright www.yotaku.cn 2016
 */


namespace Addons\ArticleToExcel\Controller;
use Home\Controller\AddonsController;
use Common\Controller\Addon;

class GetExcelController extends AddonsController{
    public function download(){
        $cate_id = I("cate_id",0);
        trace($cate_id,'文档分类');
        if($cate_id == 0){
            $this->error('无分类ID');
        }

        //TODO:获取文档数组
        $Document = D("Home/Document");
        $articles = $Document->lists($cate_id);
        foreach($articles as &$v){
            $detail = $Document->detail($v['id']);
            $v = array_merge($detail,$v);
        }unset($v);
//        dump($articles); // 全部文档获取




        //获取配置
        $config = $this->getConfig('ArticleToExcel');
        $fields = $config['fields'];
        $fields = explode(',',$fields);

        //过滤文档数组
        foreach($articles as &$article){
            foreach($article as $k=>$v){
                if(!in_array($k, $fields)){
                    unset($article[$k]);
                }
            }
        }


        //TODO:创建表格文件并下载
        $this->createExcel($articles);



    }

    private function createExcel($data){

        /** Error reporting */
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        date_default_timezone_set('Europe/London');

        if (PHP_SAPI == 'cli')
            die('This example should only be run from a Web Browser');

        /** Include PHPExcel */
        require_once dirname(__FILE__) . './../Tool/Excel/PHPExcel.php';


// Create new PHPExcel object
        $objPHPExcel = new \PHPExcel();

// Set document properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");







        //获取字段与横坐标
        $column = array();
        $start = 'A';
        foreach($data[0] as $k=>$v){
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($start.'1', $k);
            $start++;
        }unset($v);


        //表格数据赋值
        foreach($data as $key=>$value){
            $start = 'A';
            foreach($data[$key] as $k=>$v){
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue($start.($key+2), $v);
                $start++;
            }
        }


// Add some data
//        $objPHPExcel->setActiveSheetIndex(0)
//            ->setCellValue('A1', 'Hello')
//            ->setCellValue('B2', 'world!')
//            ->setCellValue('C1', 'Hello')
//            ->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
//        $objPHPExcel->setActiveSheetIndex(0)
//            ->setCellValue('A4', 'Miscellaneous glyphs')
//            ->setCellValue('A5', '内容');






//die();



// Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


// Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="message.xlsx"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }




    /**
     * 获取插件的配置数组
     */
    final public function getConfig($name=''){
        static $_config = array();
        if(empty($name)){
            $name = $this->getName();
        }
        if(isset($_config[$name])){
            return $_config[$name];
        }
        $config =   array();
        $map['name']    =   $name;
        $map['status']  =   1;
        $config  =   M('Addons')->where($map)->getField('config');
        if($config){
            $config   =   json_decode($config, true);
        }else{
            $temp_arr = include $this->config_file;
            foreach ($temp_arr as $key => $value) {
                if($value['type'] == 'group'){
                    foreach ($value['options'] as $gkey => $gvalue) {
                        foreach ($gvalue['options'] as $ikey => $ivalue) {
                            $config[$ikey] = $ivalue['value'];
                        }
                    }
                }else{
                    $config[$key] = $temp_arr[$key]['value'];
                }
            }
        }
        $_config[$name]     =   $config;
        return $config;
    }

    final public function getName(){
        $class = get_class($this);
        return substr($class,strrpos($class, '\\')+1, -5);
    }
}